﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using METU_CMT.Business;

namespace METU_CMT
{
    public partial class ShowScheduleScreen : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindSchedule();
            }
        }

        private void BindSchedule()
        {
            Course _currentCourse = EntityFactory.GetCurrentCourse(UserType.Student);

            dtgSchedule.DataSource = _currentCourse.GetScheduleWithWork();
            dtgSchedule.DataBind();
        }

        protected void OnLnkBtnDownloadClicked(object sender, EventArgs e)
        {
            GridViewRow _gridViewRow = (GridViewRow)((LinkButton)sender).NamingContainer;
            int _teamId = CommonMethods.GetIdFromGridViewRow(_gridViewRow);

            Team _team = new Team(_teamId);
            int _eventId;
            if (int.TryParse(((HiddenField)_gridViewRow.FindControl("hfEventId")).Value, out _eventId) == false)
            {
                return;
            }

            Event _event = new Event(_eventId);
            _team.DownloadDeliverable(_event);
        }

        protected void OnLnkBtnDownloadAllDocumentsClicked(object sender, EventArgs e)
        {
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);
            Team _team = _currentCourse.GetTeamOfStudent((Student)EntityFactory.User);
            _currentCourse.DownloadDocumentsOfTeam(_team);
        }

        protected void OnLnkBtnUploadClicked(object sender, EventArgs e)
        {
            GridViewRow _gridViewRow = (GridViewRow)((LinkButton)sender).NamingContainer;
            int _teamId = CommonMethods.GetIdFromGridViewRow(_gridViewRow);
            Team _team = new Team(_teamId);

            int _eventId;
            if (int.TryParse(((HiddenField)_gridViewRow.FindControl("hfEventId")).Value, out _eventId) == false)
            {
                return;
            }

            Event _event = new Event(_eventId);
            ////TODO: Fill up the deliverable

            if(_event.DueDate.CompareTo(DateTime.Now) < 0 )
            {
                MsgBox1.alert("You cannot upload a document since due date has passed!");
                return;
            }

            FileUpload _fileUpload = (FileUpload)_gridViewRow.FindControl("fuDocumentUpload");
            StringBuilder _dosyaAdi = new StringBuilder();
            DateTime _now = DateTime.Now;

            if (string.IsNullOrEmpty(_fileUpload.FileName))
            {
                //ShowAlert("Lütfen eklemek istediğiniz dosyayı seçiniz...");
                return;
            }
            HttpPostedFile _myFile = _fileUpload.PostedFile;
            string _fileExt = Path.GetExtension(_fileUpload.FileName);

            if (string.IsNullOrEmpty(_fileExt))
            {
                //ShowAlert("Yüklemek istediğiniz dosyanın uzantısı bulunamadı.");
                return;
            }

            if (_myFile.ContentLength > 10500000)
            {
                //ShowAlert("Yükleyeceğiniz dosyanın boyutu 10 MB sınırını geçmemelidir.");
                return;
            }
            if (!_fileExt.ToLower().Equals(".doc") && !_fileExt.ToLower().Equals(".docx") &&
                !_fileExt.ToLower().Equals(".txt") && !_fileExt.ToLower().Equals(".xls") &&
                !_fileExt.ToLower().Equals(".xlsx") && !_fileExt.ToLower().Equals(".pdf") &&
                !_fileExt.ToLower().Equals(".ppt") && !_fileExt.ToLower().Equals(".pptx") &&
                !_fileExt.ToLower().Equals(".jpg") && !_fileExt.ToLower().Equals(".bmp") &&
                !_fileExt.ToLower().Equals(".png") && !_fileExt.ToLower().Equals(".rtf") &&
                !_fileExt.ToLower().Equals(".jpeg"))
            {
                //ShowAlert(
                //    "Yalnızca Word, Excel, PowerPoint, PDF, Resim ve Video tipinde dosyalar yükleyebilirsiniz.");
                return;
            }
            if (_dosyaAdi.ToString().Contains("$"))
            {
                //TODO: Log: file name cannot contain $
                return;
            }

            _dosyaAdi.Append(
                Path.GetFileNameWithoutExtension(_fileUpload.FileName));
            _dosyaAdi.Append("$" + EntityFactory.User.UserId + "_");
            _dosyaAdi.Append(_now.ToString("yyyyMMddHHmmss"));
            StringBuilder _savePath =
                new StringBuilder(Server.MapPath("~/StudentDocuments/") + _dosyaAdi + _fileExt);

            _fileUpload.PostedFile.SaveAs(_savePath.ToString());

            _fileUpload.Dispose();

            Deliverable _deliverable = new Deliverable
            {
                Event = _event,
                DocType = _fileExt,
                File = _dosyaAdi + _fileExt,
                UploadTime = _now,
                RealFileName = _fileUpload.FileName
            };


            _team.UploadDeliverable(_deliverable, EntityFactory.User.UserId);

            BindSchedule();

        }

        protected void OnDtgSchedulePreRender(object sender, EventArgs e)
        {
            foreach (GridViewRow _dataGridRow in dtgSchedule.Rows)
            {
                EventTableAdapter _eventTableAdapter = new EventTableAdapter();

                int _eventId;
                if (int.TryParse(((HiddenField)_dataGridRow.FindControl("hfEventId")).Value, out _eventId) == false)
                {
                    return;
                }

                DateTime _dueDate = _eventTableAdapter.GetDueDate(_eventId);

                if (_eventTableAdapter.GetSubmissionExists(_eventId) == false)
                {
                    _dataGridRow.FindControl("lnkBtnUpload").Visible = false;
                    _dataGridRow.FindControl("fuDocumentUpload").Visible = false;
                    ((LinkButton)_dataGridRow.FindControl("lnkBtnDownload")).Enabled = false;
                }

                if( _dueDate.CompareTo(DateTime.Now) < 0)
                {
                    _dataGridRow.FindControl("lnkBtnUpload").Visible = false;
                    _dataGridRow.FindControl("fuDocumentUpload").Visible = false;
                }
            }
        }

        protected void OnLnkBtnExportToGoogleCalenderClicked(object sender, EventArgs e)
        {
            Response.Redirect("~/ExportToGoogleCalendarScreen.aspx");
        }
    }
}